import gtk, gtk.glade, uprender.canvas, uprender.base,uprender.GeneItem
import GeneName
#import upsteamator
import cairo
import goocanvas
import upcore.core
import datetime
import matplotlib.pyplot as pp
class Loader():
    def __init__(self):
        self.wTree  = gtk.glade.XML("loader.glade")
        self.window = self.wTree.get_widget("window1")
        self.window.connect("delete-event", self.end)
        self.window.set_modal(True)
    def show(self):
        self.window.show_all()

    def end(self, w ):
        self.window.destroy()


class maingui():
    def __init__(self):
        self.wTree = gtk.glade.XML("guimain.glade")
        self.window = self.wTree.get_widget("window1")
        self.loader = self.wTree.get_widget("window2")
        self.loader.resize(800,600)
        self.window.connect("destroy", self.end)
        self.window.resize(800,600)
        self.scrwin = self.wTree.get_widget("scrolledwindow1")
        self.searchbutton = self.wTree.get_widget("searchbutton")
        self.entrybox = self.wTree.get_widget("entrybox")
        self.entrybox.connect("activate", self.search_clicked)
        self.searchbutton.connect("clicked",self.search_clicked)
        self.repno = self.wTree.get_widget("repnocom")
        self.repno.connect("changed", self.repchanged )
        self.canvas = None
        self.upstream = None
        self.repnoint = 1
        self.window.show_all()
    def repchanged(self, w):

        self.repnoint = int(w.get_active_text())
    def do_events(self):
        while gtk.events_pending():
                gtk.main_iteration()

    def new_canvas(self):
        if self.canvas is not None :

            self.scrwin.remove(self.canvas)
            self.canvas = None
            del self.canvas
            self.upstream = None
            del self.upstream

        self.canvas = uprender.canvas.Canvas()
        self.scrwin.add(self.canvas)
        #self.upstream = upsteamator.Upstream(self.entrybox.get_text(), self.repnoint)
        #self.upstream = upcore.core.helper("refseq1000.txt", self.entrybox.get_text())
        data_file  = "seq-2kb"
        x = upcore.core.Parse(data_file,"r")
        found_sites = x.motif_finder(self.entrybox.get_text(), x.run())
        self.width = 0
        self.height = 0
        #GENE_NUMBER = len(self.upstream.motif_list_feature)
        height = 0
        feature_no = 0
        text = "Motif searched: " + self.entrybox.get_text() + " Data file: " +  data_file + " Date:" + datetime.datetime.now().strftime("%c") + " RENDERED BY UPSTREAM "
        self.text = goocanvas.Text(parent=self.canvas.get_root_item() ,x=15,y=5, text = text, fill_color = "black", font="consolas")

        list_of_motif_pos =[]
        gene_no = 0

        cons_file = open("rangeforcons_%s.txt" % self.entrybox.get_text(),"w")
        gene_file = open("genefile_%s.txt" % self.entrybox.get_text() ,"w")

        for feature in found_sites:
            #gene = self.upstream.motif_list_feature[j]
            print "%s processed successfully in range %s" % (feature[0].name, feature[0].chr)
            gene_file.write("%s \n" % feature[0].name)

            gene_no +=1
            list_of_pos=[]

            for k in feature[1]:
                list_of_pos.append([k.start(), k.end()])
                print k.start(),k.end
                list_of_motif_pos.append(k.start() - 1000)

                cons_file.write("%s %d %d %s \n" % (feature[0].chr, k.start() + int( feature[0].start) -10 , k.end() + int ( feature[0].start) +10, feature[0].name) )
            x = uprender.GeneItem.Gene(feature[0], self.canvas, list_of_pos, feature_no, height)
            feature_no +=1
            height += x.size[1]
            self.canvas.set_my_bounds(x.size[0], height + 50)
            self.width = x.size[0]
            self.height = height + 50
        gene_file.close()
        cons_file.close()
        print "%s genes will be graphed. please wait." % gene_no
        from  matplotlib import pyplot as pp
        from scipy import stats

        print stats.normaltest(list_of_motif_pos, axis=None)

        pp.hist(list_of_motif_pos, 39)
        pp.xlabel("Relative location to TSS(bp)")
        pp.ylabel("Number of genes")
        pp.savefig("%s_hist.png" % self.entrybox.get_text())
        pp.clf()

        self.canvas.show()
        self.window.show_all()

        DRAW_WIDTH = self.width
        DRAW_HEIGHT = self.height


        s = cairo.ImageSurface(cairo.FORMAT_ARGB32, DRAW_WIDTH, DRAW_HEIGHT)
        c1 = cairo.Context(s)
        c1.rectangle(0,0,DRAW_WIDTH,DRAW_HEIGHT)
        c1.set_source_rgb(1,1,1)
        c1.fill()

        self.canvas.render(c1)


        s.write_to_png(self.entrybox.get_text() + ".png")

    def search_clicked(self,w):

        if self.entrybox.get_text() <> "":

            self.new_canvas()

    def end(self,w):
        gtk.main_quit()

x = maingui()
gtk.main()
